package com.xiaocg.demowebflux.service;

import com.xiaocg.demowebflux.entity.Person;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Service
public class PersonService {

    private final Map<Long, Person> personMap = new HashMap<>();

    @PostConstruct
    public void  init(){
        personMap.put(1L,new Person(1L,"xiao"));
        personMap.put(2L,new Person(2L,"chang"));
        personMap.put(3L,new Person(3L,"gui"));
    }

    public Mono<Person> getById(Long id){
        return Mono.justOrEmpty(this.personMap.get(id));
    }

    public Flux<Person> listAll(){
        return Flux.fromIterable(this.personMap.values());
    }

    public Mono<Void> add(Mono<Person> personMono){
        return personMono.doOnNext(person -> {
            this.personMap.put(person.getId(),person);
        }).thenEmpty(Mono.empty());
    }
}
